const fs = require('fs')
const path = require('path')
const { dialog, shell } = require('electron').remote

window.onload = function () {
  /*拖拽的目标对象------ document 监听drop 并防止浏览器打开客户端的图片*/
  document.ondragover = function (e) {
    e.preventDefault() //只有在ondragover中阻止默认行为才能触发 ondrop 而不是 ondragleave
  }
  document.ondrop = function (e) {
    e.preventDefault() //阻止 document.ondrop的默认行为  *** 在新窗口中打开拖进的图片
  }

  new Vue({
    el: '#app',
    data: {
      msg: 'sdf',
      config: null,
      isShadow: false,
      isAddNew: true,
      currentId: 0,
      form: {
        name: '',
        path: '',
      },
    },
    created() {
      this.getConfig()
    },
    methods: {
      // 获取配置
      getConfig() {
        this.config = JSON.parse(fs.readFileSync('./config.json'))
      },
      // 写入配置
      setConfig() {
        let str = JSON.stringify(this.config)
        fs.writeFileSync('./config.json', str)
      },

      // 拖动经过
      handleDragOver(item) {
        this.currentId = item.id
      },
      // 拖动离开
      handleDragLeave() {
        this.currentId = 0
      },
      // 拖动释放
      handleDrop(event, item) {
        const list = Array.from(event.dataTransfer.files)
        const that = this
        list.forEach((file) => {
          // 解析路径
          const pathObj = path.parse(file.path)

          const rs = fs.createReadStream(file.path)

          const ws = fs.createWriteStream(
            path.join(item.path, pathObj.name + pathObj.ext)
          )

          rs.pipe(ws)

          rs.on('open', function () {
            that.currentId = item.id
            that.isShadow = true
          })
          rs.on('error', function (e) {
            console.log(e)
            dialog.showMessageBox({
              // type 取值 none,info,error,question
              type: 'error',
              title: '写入失败',
              message: e,
            })
          })

          rs.on('close', () => {
            console.log('文件写入关闭')

            that.currentId = 0
            that.isShadow = false

            dialog.showMessageBox({
              // type 取值 none,info,error,question
              type: 'info',
              title: '文件信息',
              message: '写入完成',
            })
          })
        })
      },
      // 点击打开目录
      handleClick(item) {
        shell.openPath(item.path)
      },
      // 新增
      handleAddClick() {
        this.isAddNew = true
      },
      submitNew() {
        const newItem = {
          id: new Date().getTime().toString(),
          ...this.form,
        }
        this.config.pathList.push(newItem)
        this.setConfig()
        this.isAddNew = false
      },
    },
  })
}
